<?php
/**
 * User: @lose
 * Date: 2021/8/26
 * Time: 9:48 上午
 */

namespace Frieza\Modules\Circle\Controllers;

use Doraemon\model\Circle\CircleBaseInfo as mCircleBaseInfo;
use Doraemon\model\Circle\CircleProportion as mCircleProportion;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CircleProportionController
{
    public function edit(Content $content)
    {
        Admin::script($this->setScript());
        $circleList = mCircleBaseInfo::select('*', ['circle_status' => mCircleBaseInfo::STATUS_NORMAL]);
        $circleIdList = array_column($circleList, 'circle_id');
        $proportionList = mCircleProportion::getListByWhere(['circle_id' => $circleIdList]);
        $proportionList = array_column($proportionList, null, 'circle_id');
        $list = [];
        foreach ($circleList as $info) {
            $list['proportion_list'][] = [
                'id' => $proportionList[$info['circle_id']]['id'],
                'circle_id' => $info['circle_id'],
                'circle_name' => $info['circle_name'],
                'proportion' => $proportionList[$info['circle_id']]['proportion']
            ];
        }

        $form = new Form($list);
        $form->table('proportion_list', '', function ($table) {
            $table->hidden('id', 'id');
            $table->hidden('circle_id', '圈子id');
            $table->text('circle_name', '圈子名称')->readonly();
            $table->text('proportion', '流量比例')->default(0)->required();
        });
        $form->disableReset();
        $form->action('/admin/circle/proportion/save');
        return $content
            ->header('圈子流量比例调整')
            ->breadcrumb(['text' => '圈子管理', 'url' => 'circle'], ['text' => '圈子流量比例调整'])
            ->row($form);
    }

    public function save(Request $request)
    {
        try {

            $params = $request->all();
            $total = array_sum(array_column($params['proportion_list'], 'proportion'));

            if($total != 100) {
                throw new \Exception('内容比例相加不等于 100%');
            }

            foreach ($params['proportion_list'] as $info) {
                $data = [
                    'proportion' => $info['proportion'],
                    'circle_id' => $info['circle_id'],
                    'admin_id' => Admin::user()->id,
                ];
                if ($info['id']) {
                    $data['edittime'] = time();
                    mCircleProportion::edit($info['id'], $data);
                } else {
                    $data['addtime'] = time();
                    mCircleProportion::add($data);
                }
            }

            $success = new MessageBag([
                'title' => '保存成功，将于 1 小时后生效'
            ]);
            return back()->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    // 删除圈子比例配置页面的新增和移除按钮
    private function setScript()
    {
        return <<<SCRIPT
    $("div").remove(".remove");
    $("div").remove(".add");
SCRIPT;
    }
}